var React = require('react');
var ReactDOM=require('react-dom');
var $=require('jquery');
var TodoItem=require('./todoItem.jsx');
import {browserHistory,Link} from 'react-router';

var App = React.createClass({
	getInitialState: function() {
		return {
		  todolist: []
		};
	},
	propTypes:{
		uid:React.PropTypes.number.isRequired
	},
	getDefaultProps: function() {
    return {
	      uid: 0
	    };
  	},
	componentDidMount:function(){	
		if(this.props.params.uid>0)
		{
			this.getData();
		}		
	},
  	getData:function(){
  		var self=this;
  		$.ajax({
            type: "POST",
            url: "http://www.see2eyes.cn/Todo/GetlistByUid",
            dataType: "json",
            data: "uid="+this.props.params.uid,
            success: function (result) {                
                var arr=JSON.parse(result.todolist); 
                self.setState({
					todolist:arr
				})
            }
        });
  	},
  	saveData:function(ajaxData){
		$.ajax({
            type: "POST",
            url: "http://www.see2eyes.cn/Todo/Save",
            dataType: "json",
            data: "callback=react&uid="+this.props.params.uid+"&todolist="+JSON.stringify(ajaxData),
            success: function (result) {
            }
        });
  	},
  	deleteById:function(id){	
  		if(!confirm("删除后不可恢复，确认删除吗？"))
  		{
  			return false;
  		}
  		var arr=this.state.todolist;
  		var idx=arr.length;
  		arr.forEach(function(item,index){
  			if(item.id==id)
  			{
  				idx=index;
  				return;
  			}
  		})  		
  		arr.splice(idx,1);  		
		var newList=arr.map(function(item,index){
  			item.id=index;  			
  			return item;
  		})
		this.setState({
			todolist:newList
		})
		this.saveData(newList);
  	},
  	modifyTodo:function(todo){
  		var arr=this.state.todolist;
  		var idx=arr.length;
  		arr.forEach(function(item,index){
  			if(item.id==todo.id)
  			{
  				idx=index;
  				return;
  			}
  		})  		
  		arr.splice(idx,1,todo);  		
		var newList=arr.map(function(item,index){
  			item.id=index;  			
  			return item;
  		})
  		console.log(arr);
		this.setState({
			todolist:arr
		})
		//this.saveData(newList);
  	},
	handleClick:function(e){
		if(e.nativeEvent.keyCode==13){
			var inputTxt=this.refs.addbox.value;
			var todolist=this.state.todolist;
			//只能保存10条记录
			if(todolist.length>=10)
			{
				alert("你又不是VIP，干嘛要保存那么多！");
				return false;
			}
			//查看是否存在此事项
			var isExist=false;
			todolist.forEach(function(item,idx){				
				if(item.txt==inputTxt)
				{
					isExist=true;
					return;
				}
			})
			this.setState({
				defaultTodo:inputTxt
			});
			this.refs.addbox.value="";
			if(isExist)
			{
				alert("已存在此事项！不能重复添加");
				return false;
			}
			else
			{
				let newId=todolist.length+1;
				let obj={
					id:newId,
					txt:inputTxt,
					complete:false
				};
				todolist.unshift(obj);
				this.setState({
					todolist:todolist
				})
				//保存到数据库
				this.saveData(todolist);
			}
		}
	},
	 componentDidUpdate (prevProps) {

        console.log("componentDidUpdate",this.props.params.uid,prevProps.params.uid);
    },
     componentWillReceiveProps:function(nextProps){
   
        console.log("componentWillReceiveProps",this.props.params.uid,nextProps.params.uid);
    
    },
    routerWillLeave:function(nextLocation) {
        console.log("routerWillLeave",nextLocation);
    },
  	render: function () {
  		var self=this;
  		var todoitem=this.state.todolist.map(function(item,index){
  			return(
  					<TodoItem modifyTodo={self.modifyTodo} deleteById={self.deleteById} key={'td'+index} todo={item} />
  				)
  		});
	    return (
	      <ul className="todo-list">
	      	<li>
	      		<Link to="/todo/1" activeClassName="active">TODO1</Link>
	      	</li>
	      	<li>
	      		<Link to="/todo/2" activeClassName="active">TODO2</Link>
	      	</li>
			<li className="todo">
				<input className="addBox" type="text" defaultValue={this.state.defaultTodo} 
					ref="addbox" onKeyUp={this.handleClick} placeholder="what needs to do?" />	
			</li>			
			{todoitem}		
		</ul>
	    );
	  }
});

module.exports = App;